﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using One.Framework;
using Money.Data;
using Money.Interfaces;
using One.Web;
using One.Web.UI.WebControls;
using Resources;

public partial class Admin_EditMemorizedTransaction : System.Web.UI.Page
{
    #region fields

    private IMemorizedTransactionService memorizedTransactionService;
    private ICategoryService categoryService;
    private IRefService refService;
    private IClassService classService;
    private IAccountService accountService;
    private MemorizedTransaction memorizedTransaction = null;
    private int memorizedTransactionId;
    private string redirectUrl = "MemorizedTransactionManagement.aspx";
    private int success;
    private List<Ref> refList;
    private List<Class> classList;
    private List<Account> accountList;

    #endregion

    #region events

    protected void Page_Load(object sender, EventArgs e)
    {
        memorizedTransactionService = ServiceFactory.Create<IMemorizedTransactionService>();
        categoryService = ServiceFactory.Create<ICategoryService>();
        refService = ServiceFactory.Create<IRefService>();
        classService = ServiceFactory.Create<IClassService>();
        accountService = ServiceFactory.Create<IAccountService>();

        GetParams();
        LoadData();
        AddRules();
        if (!IsPostBack)
        {
            UpdateView();
        }
    }

    protected void ChangeTransactionType(object sender, EventArgs e)
    {
        divAccountTo.Visible = false;
        switch (int.Parse(cbTransactionType.SelectedValue))
        {
            case (int)TransactionType.Deposit:
                labelAccount.Text = Resources.Strings.ToAccount;
                break;
            case (int)TransactionType.Payment:
                labelAccount.Text = Resources.Strings.FromAccount;
                break;
            default:
                labelAccount.Text = Resources.Strings.FromAccount;
                divAccountTo.Visible = true;
                break;
        }
    }

    protected void AddOrUpdate(object sender, EventArgs e)
    {
        if (validationManager.Validate())
        {
            bool isAdd = false;
            if (memorizedTransaction == null)
            {
                memorizedTransaction = new MemorizedTransaction();
                isAdd = true;
            }
            memorizedTransaction.TransactionType = int.Parse(cbTransactionType.SelectedValue);

            if (!isAdd)
            {
                memorizedTransaction.Account = accountService.GetAccountById(int.Parse(cbAccount.SelectedValue));
                memorizedTransaction.Category = categoryService.GetCategoryById(ucCategory.CategoryID);
                memorizedTransaction.Ref = refService.GetRefById(int.Parse(cbRef.SelectedValue));
                memorizedTransaction.Class = classService.GetClassById(int.Parse(cbClass.SelectedValue));
            }

            if (int.Parse(cbTransactionType.SelectedValue) == (int)TransactionType.Transfer)
            {
                if (memorizedTransaction.Account1 == null)
                {
                    memorizedTransaction.Account1 = new Account() { AccountId = int.Parse(cbAccountTo.SelectedValue) };
                }
                memorizedTransaction.Account1.AccountId = int.Parse(cbAccountTo.SelectedValue);
            }
            else
            {
                memorizedTransaction.Account1 = null;
            }
            memorizedTransaction.AccountId = int.Parse(cbAccount.SelectedValue);
            memorizedTransaction.CategoryId = ucCategory.CategoryID;
            memorizedTransaction.RefId = int.Parse(cbRef.SelectedValue);
            memorizedTransaction.ClassId = int.Parse(cbClass.SelectedValue);
            memorizedTransaction.PayMan = tbPayMan.Text;
            memorizedTransaction.Amount = decimal.Parse(tbAmount.Text);
            memorizedTransaction.Note = tbNote.Text;

            if (isAdd)
            {
                memorizedTransactionService.CreateMemorizedTransaction(memorizedTransaction);
                success = 1;
            }
            else
            {
                memorizedTransactionService.UpdateMemorizedTransaction(memorizedTransaction);
                success = 2;
            }
            Response.Redirect(string.Format("{0}?success={1}", redirectUrl, success));
        }
    }


    #endregion

    #region private functions

    private void GetParams()
    {
        memorizedTransactionId = QueryStringUtility.GetInt32("transactionId", 0);
    }

    private void LoadData()
    {
        if (memorizedTransactionId != 0)
        {
            try
            {
                memorizedTransaction = memorizedTransactionService.GetMemorizedTransactionById(memorizedTransactionId);
                if (memorizedTransaction != null && memorizedTransaction.Account.UserId != WebSession.CurrentUser.UserId)
                    memorizedTransaction = null;
            }
            catch
            {
                memorizedTransaction = null;
            }
        }
        accountList = accountService.GetAccounts(WebSession.CurrentUser.UserId, AccountOrderBy.DisplayName.ToString(), OrderDirection.ASC.ToString());
        refList = refService.GetRefs();
        classList = classService.GetClasses();

    }

    private void UpdateView()
    {
        AddTransactionType();
        AddFromAccounts();
        AddToAccounts();
        AddClasses();
        AddRefs();
        (Master as Admin_MasterPage).SelectedTab = "memorizedTransactionManagement";
        if (memorizedTransaction == null)
        {
            pageTitle.Text = Resources.Strings.AddMemorizedTransaction;
            btAddOrUpdate.Text = Resources.Strings.Add;
        }
        else
        {
            pageTitle.Text = Resources.Strings.UpdateMemorizedTransaction;
            btAddOrUpdate.Text = Resources.Strings.Update;

            cbTransactionType.SelectedValue = memorizedTransaction.TransactionType.ToString();
            cbAccount.SelectedValue = memorizedTransaction.Account.AccountId.ToString();
            cbRef.SelectedValue = memorizedTransaction.Ref.RefId.ToString();
            cbClass.SelectedValue = memorizedTransaction.Class.Id.ToString();
            tbPayMan.Text = memorizedTransaction.PayMan;
            tbAmount.Text = memorizedTransaction.Amount.HasValue ? memorizedTransaction.Amount.Value.ToString() : "0";
            tbNote.Text = memorizedTransaction.Note;
            ucCategory.CategoryName = memorizedTransaction.Category.Name;
            ucCategory.CategoryID = memorizedTransaction.Category.Id;

            if (memorizedTransaction.TransactionType == (int)TransactionType.Transfer)
                cbAccountTo.SelectedValue = memorizedTransaction.Account1.AccountId.ToString();
        }
        ChangeTransactionType(null, null);
    }

    private void AddFromAccounts()
    {
        cbAccount.DataSource = accountList;
        cbAccount.DataTextField = "DisplayName";
        cbAccount.DataValueField = "AccountId";
        cbAccount.DataBind();
    }

    private void AddToAccounts()
    {
        cbAccountTo.DataSource = accountList;
        cbAccountTo.DataTextField = "DisplayName";
        cbAccountTo.DataValueField = "AccountId";
        cbAccountTo.DataBind();
    }

    private void AddRefs()
    {
        cbRef.DataSource = refList;
        cbRef.DataTextField = "Name";
        cbRef.DataValueField = "RefId";
        cbRef.DataBind();
    }

    private void AddClasses()
    {
        cbClass.DataSource = classList;
        cbClass.DataTextField = "Name";
        cbClass.DataValueField = "Id";
        cbClass.DataBind();
    }

    private void AddTransactionType()
    {
        cbTransactionType.DataSource = MoneyUtilities.GetEnumList(typeof(TransactionType));
        cbTransactionType.DataTextField = "Value";
        cbTransactionType.DataValueField = "Key";
        cbTransactionType.DataBind();
    }

    private void AddRules()
    {
        validationManager.AddRule(new ValueRequiredRule(tbPayMan, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));
        validationManager.AddRule(new ValueRequiredRule(ucCategory.TextBoxName, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));
        validationManager.AddRule(new DecimalValueRule(tbAmount, Strings.DecimalValueErrorMessage, Strings.DecimalValueHint));
        validationManager.AddRule(new CustomeValidatorRule(tbAmount, Strings.ValueRangeErrorMessage, Strings.ValueRangeErrorHint, ValidBalance));

        validationManager.Notifier = new BalloonNotifier();
    }

    private void ValidBalance(string strValue, out bool isValid)
    {
        try
        {
            decimal value = decimal.Parse(strValue);
            isValid = value >= 0;
        }
        catch
        {
            isValid = false;
        }
    }

    #endregion

    #region public functions



    #endregion 
}
